import { Injectable, Inject } from '@nestjs/common';
import { Model } from 'mongoose';
import { DBCONSTANTS } from '../database/db.constants';
import { Team } from './interface/team.interface';

@Injectable()
export class TeamService {
  @Inject(DBCONSTANTS.teamModel)
  private readonly teamModel: Model<Team>;

  /**
   * 查询用户下的团队
   * @param userId 用户id
   */
  async findTeamList(userId: string): Promise<Team[]> {
    return await this.teamModel.find({ userId });
  }

  /**
   * 根据团队名称查询团队
   * @param teamName
   */
  async findTeamByTeamName(teamName: string) {
    return await this.teamModel.findOne({ teamName });
  }

  /**
   * 创建一个团队
   * @param team
   */
  async createTeam(team: Team): Promise<Team> {
    const newTeam = new this.teamModel(team);
    return await newTeam.save();
  }

  /**
   * 切换激活的团队
   * @param userId 用户id
   * @param teamId 团队id
   */
  async changeTeam(userId: string, teamId: string): Promise<Team> {
    await this.teamModel.updateMany({ userId }, { status: 0 });
    return await this.teamModel.updateOne({ _id: teamId }, { status: 1 });
  }

  /**
   * 退出加入或自建的团队
   * @param teamId 团队id
   */
  async deleteTeam(teamId: string) {
    return await this.teamModel.findByIdAndRemove(teamId);
  }

  /**
   * 查询当前用户下激活的团队
   * @param userId
   */
  async findTeamForActive(userId: string) {
    return await this.teamModel.findOne({ userId, status: 1 });
  }
}
